﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Data.SqlServerCe;

namespace CEQuery
{
    public partial class CreateTable : Form
    {
        public string SelectedTable { get; set; }
        public string ConnectionString { get; set; }
        public string TableScript { get; private set; }

        private bool isValid;
        private bool isEditMode;
        private DataSet dsTable;
        private DataSet dsPks;
        private string pkName;
        private List<ColumnInfo> originalTableInfo;

        public CreateTable()
        {
            InitializeComponent();
        }

        private void CreateTable_Load(object sender, EventArgs e)
        {
            try
            {
                isValid = false;
                isEditMode = false;
                if (!string.IsNullOrEmpty(SelectedTable) && !string.IsNullOrEmpty(ConnectionString))
                {
                    isEditMode = true;
                    txtTbl.Text = SelectedTable;
                    txtTbl.Enabled = false;
                    this.Text = "Edit Table";
                    dgTbl.RowsRemoved -= new DataGridViewRowsRemovedEventHandler(dgTbl_RowsRemoved);
                    GetTableInfo();
                    dgTbl.RowsRemoved += new DataGridViewRowsRemovedEventHandler(dgTbl_RowsRemoved);
                    if (dgTbl.Rows.Count > 0)
                    {
                        dgTbl.Rows[0].Selected = true;
                        pgTbl.SelectedObject = (ColumnProp)dgTbl.Rows[0].Tag;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetTableInfo()
        {
            if (!string.IsNullOrEmpty(ConnectionString))
            {
                dsTable = new DataSet();
                dsPks = new DataSet();
                SqlCeDataAdapter da;
                SqlCeCommand cmd;
                using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
                {
                    cmd = new SqlCeCommand();
                    cmd.Connection = connection;
                    connection.Open();
                    cmd.CommandText =
                        "SELECT     Column_name, is_nullable, data_type, character_maximum_length, numeric_precision,numeric_scale, autoinc_increment, column_hasdefault, column_default, autoinc_seed " +
                        "FROM         information_schema.columns " +
                        "WHERE     (table_name = '" + SelectedTable + "') " +
                        "ORDER BY ordinal_position ASC ";

                    da = new SqlCeDataAdapter(cmd);                    
                    da.Fill(dsTable);

                    cmd.CommandText =
                        "SELECT u.COLUMN_NAME,c.Constraint_Name " +
                        "FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS c INNER JOIN " +
                        "INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS u ON c.CONSTRAINT_NAME = u.CONSTRAINT_NAME " +
                        "WHERE u.TABLE_NAME = '" + SelectedTable + "' and c.CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY ORDINAL_POSITION";

                    da = new SqlCeDataAdapter(cmd);
                    da.Fill(dsPks);

                    connection.Close();
                }
                
                //dgTbl.Rows.Add(dsTable.Tables[0].Rows.Count);

                for (int index = 0; index <= dsTable.Tables[0].Rows.Count; index++)
                {
                    dgTbl.Rows.Add();
                }

                //Create Saved Info
                originalTableInfo = new List<ColumnInfo>();
                if (dsPks.Tables[0].Rows.Count > 0)
                {
                    pkName = dsPks.Tables[0].Rows[0]["Constraint_Name"].ToString();
                }
                for (int index = 0; index < dsTable.Tables[0].Rows.Count; index++)
                {
                    ColumnInfo columnInfo = new ColumnInfo();
                    columnInfo.ColIndex = index;
                    columnInfo.ColumnName = dsTable.Tables[0].Rows[index]["Column_name"].ToString();
                    columnInfo.DataType = dsTable.Tables[0].Rows[index]["data_type"].ToString();
                    columnInfo.MaxLength = dsTable.Tables[0].Rows[index]["character_maximum_length"] != null && dsTable.Tables[0].Rows[index]["character_maximum_length"].ToString() != string.Empty ? int.Parse(dsTable.Tables[0].Rows[index]["character_maximum_length"].ToString()) : new Nullable<int>();
                    columnInfo.IsNullable = dsTable.Tables[0].Rows[index]["is_nullable"].ToString() == "NO" ? false : true;
                    if (dsPks.Tables[0].Select("COLUMN_NAME = '" + dsTable.Tables[0].Rows[index]["Column_name"].ToString() + "'").Length > 0)
                    {
                        columnInfo.IsPk = true;
                    }
                    
                    dgTbl.Rows[index].Cells[0].Value = dsTable.Tables[0].Rows[index]["Column_name"].ToString();
                    dgTbl.Rows[index].Cells[0].ReadOnly = true;
                    ((DataGridViewComboBoxCell)dgTbl.Rows[index].Cells[1]).Value = dsTable.Tables[0].Rows[index]["data_type"].ToString();
                    dgTbl.Rows[index].Cells[2].Value = dsTable.Tables[0].Rows[index]["character_maximum_length"].ToString();
                    dgTbl.Rows[index].Cells[3].Value = dsTable.Tables[0].Rows[index]["is_nullable"].ToString() == "NO" ? false : true;                    
                    if (dsPks.Tables[0].Select("COLUMN_NAME = '" + dsTable.Tables[0].Rows[index]["Column_name"].ToString() + "'").Length > 0)
                    {
                        dgTbl.Rows[index].Cells[4].Value = true;
                    }

                    ColumnProp prop = new ColumnProp();
                    dgTbl.Rows[index].Tag = prop;
                    prop.DefaultValue = dsTable.Tables[0].Rows[index]["column_default"].ToString();                    
                    prop.IdentityIncrement = !string.IsNullOrEmpty(dsTable.Tables[0].Rows[index]["autoinc_increment"].ToString()) ? int.Parse(dsTable.Tables[0].Rows[index]["autoinc_increment"].ToString()) : 0;
                    prop.IdentitySeed = !string.IsNullOrEmpty(dsTable.Tables[0].Rows[index]["autoinc_seed"].ToString()) ? int.Parse(dsTable.Tables[0].Rows[index]["autoinc_seed"].ToString()) : 0;
                    prop.Identity = prop.IdentityIncrement > 0 && prop.IdentitySeed > 0;
                    prop.Precision = !string.IsNullOrEmpty(dsTable.Tables[0].Rows[index]["numeric_precision"].ToString()) ? int.Parse(dsTable.Tables[0].Rows[index]["numeric_precision"].ToString()) : 0;
                    prop.Scale = !string.IsNullOrEmpty(dsTable.Tables[0].Rows[index]["numeric_scale"].ToString()) ? int.Parse(dsTable.Tables[0].Rows[index]["numeric_scale"].ToString()) : 0;
                    
                    columnInfo.ColProp = new ColumnProp();
                    columnInfo.ColProp.DefaultValue = prop.DefaultValue;
                    columnInfo.ColProp.Identity = prop.Identity;
                    columnInfo.ColProp.IdentityIncrement = prop.IdentityIncrement;
                    columnInfo.ColProp.IdentitySeed = prop.IdentitySeed;
                    columnInfo.ColProp.Precision = prop.Precision;
                    columnInfo.ColProp.Scale = prop.Scale;

                    originalTableInfo.Add(columnInfo);
                }

                dgTbl.Rows.RemoveAt(dgTbl.Rows.Count - 2);
            }
        }

        private void dgTbl_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            try
            {
                if (e.RowIndex > 0)
                {
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("bigint");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("binary");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("bit");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("datetime");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("float");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("image");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("int");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("money");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("nchar");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("ntext");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("numeric");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("nvarchar");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("real");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("smallint");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("tinyint");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("uniqueidentifier");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("varbinary");
                    ((DataGridViewComboBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[1]).Items.Add("rowversion");
                    dgTbl.Rows[e.RowIndex - 1].Cells[2].ReadOnly = true;
                    ((DataGridViewCheckBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[3]).Value = true;
                    ((DataGridViewCheckBoxCell)dgTbl.Rows[e.RowIndex - 1].Cells[4]).Value = false;
                    ColumnProp prop = new ColumnProp();
                    dgTbl.Rows[e.RowIndex - 1].Tag = prop;
                    pgTbl.SelectedObject = prop;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dgTbl_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0 && e.ColumnIndex == 1)
                {
                    if (dgTbl.Rows[e.RowIndex].Cells[1].Value.ToString() == "nchar" ||
                        dgTbl.Rows[e.RowIndex].Cells[1].Value.ToString() == "nvarchar" ||
                        dgTbl.Rows[e.RowIndex].Cells[1].Value.ToString() == "binary" ||
                        dgTbl.Rows[e.RowIndex].Cells[1].Value.ToString() == "varbinary")
                    {
                        dgTbl.Rows[e.RowIndex].Cells[2].ReadOnly = false;
                    }
                    else
                    {
                        dgTbl.Rows[e.RowIndex].Cells[2].Value = null;
                        dgTbl.Rows[e.RowIndex].Cells[2].ReadOnly = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dgTbl_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (!dgTbl.Rows[e.RowIndex].IsNewRow)
                {
                    isValid = true;
                    for (int index = 0; index < dgTbl.Rows[e.RowIndex].Cells.Count; index++)
                    {
                        if (!dgTbl.Rows[e.RowIndex].Cells[index].ReadOnly && dgTbl.Rows[e.RowIndex].Cells[index].Value == null)
                        {
                            dgTbl.Rows[e.RowIndex].Cells[index].ErrorText = "Please enter value";
                            isValid = false;
                        }
                        else
                        {
                            dgTbl.Rows[e.RowIndex].Cells[index].ErrorText = string.Empty;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dgTbl_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgTbl.SelectedRows.Count > 0 && !dgTbl.SelectedRows[0].IsNewRow)
                {
                    pgTbl.SelectedObject = (ColumnProp)dgTbl.SelectedRows[0].Tag;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dgTbl_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                dgTbl.Rows[e.RowIndex].Selected = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnTbl_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtTbl.Text.Trim() == string.Empty || (dgTbl.Rows.Count == 1 && dgTbl.Rows[0].IsNewRow) || !isValid)
                {
                    MessageBox.Show("Please define the columns & tablename properly");
                    return;
                }
                StringBuilder sbTbl = new StringBuilder();
                ColumnProp columnProp;
                if (!isEditMode)
                {
                    int cntPK = 0;
                    foreach (DataGridViewRow row in dgTbl.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            if (bool.Parse(row.Cells[4].Value.ToString()))
                            {
                                cntPK++;
                            }
                        }
                    }


                    sbTbl.AppendFormat("CREATE TABLE [{0}] (", txtTbl.Text.Trim());
                    foreach (DataGridViewRow row in dgTbl.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            columnProp = (ColumnProp)row.Tag;
                            sbTbl.AppendFormat("[{0}] {1}", row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString());
                            if (!row.Cells[2].ReadOnly)
                            {
                                sbTbl.AppendFormat("({0})", row.Cells[2].Value.ToString());
                            }
                            else
                            {
                                if (row.Cells[1].Value.ToString() == "numeric")
                                {
                                    sbTbl.AppendFormat("({0},{1})", columnProp.Precision > 0 ? columnProp.Precision.ToString() : "18", columnProp.Scale.ToString());
                                }
                            }
                            if ((row.Cells[1].Value.ToString() == "int" || row.Cells[1].Value.ToString() == "bigint") && columnProp.Identity && columnProp.IdentitySeed > 0 && columnProp.IdentityIncrement > 0)
                            {
                                sbTbl.AppendFormat(" IDENTITY({0},{1}) NOT NULL", columnProp.IdentitySeed.ToString(), columnProp.IdentityIncrement.ToString());
                            }
                            else
                            {
                                sbTbl.AppendFormat(" {0}", bool.Parse(row.Cells[3].Value.ToString()) ? "NULL" : " NOT NULL");
                                if (!string.IsNullOrEmpty(columnProp.DefaultValue))
                                {
                                    sbTbl.AppendFormat(" DEFAULT ({0})", columnProp.DefaultValue);
                                }
                            }

                            if (bool.Parse(row.Cells[4].Value.ToString()) && cntPK == 1)
                            {
                                sbTbl.AppendFormat(" {0}", "PRIMARY KEY");
                            }
                            sbTbl.Append(",");
                        }
                    }
                    TableScript = sbTbl.ToString().Substring(0, sbTbl.ToString().Length - 1) + ")";
                    sbTbl = new StringBuilder();
                    if (cntPK > 1)
                    {
                        sbTbl.AppendFormat("\nALTER TABLE [{0}] ADD PRIMARY KEY (", txtTbl.Text.Trim());
                        foreach (DataGridViewRow row in dgTbl.Rows)
                        {
                            if (!row.IsNewRow)
                            {
                                if (bool.Parse(row.Cells[4].Value.ToString()))
                                {
                                    sbTbl.AppendFormat("[{0}],", row.Cells[0].Value.ToString());
                                }
                            }
                        }
                        TableScript += sbTbl.ToString().Substring(0, sbTbl.ToString().Length - 1) + ")";
                    }
                }
                else
                {
                    //In Edit Mode
                    List<ColumnInfo> modifiedTableInfo = new List<ColumnInfo>();
                    foreach (DataGridViewRow row in dgTbl.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            ColumnInfo columnInfo = new ColumnInfo();
                            columnInfo.ColIndex = row.Index;
                            columnInfo.ColumnName = row.Cells[0].Value.ToString();
                            columnInfo.DataType = row.Cells[1].Value.ToString();
                            columnInfo.MaxLength = row.Cells[2].Value != null && row.Cells[2].Value.ToString().Trim() != string.Empty ? int.Parse(row.Cells[2].Value.ToString().Trim()) : new Nullable<int>();
                            columnInfo.IsNullable = bool.Parse(row.Cells[3].Value.ToString());
                            columnInfo.IsPk = bool.Parse(row.Cells[4].Value.ToString());

                            columnInfo.ColProp = new ColumnProp();
                            columnInfo.ColProp.DefaultValue = ((ColumnProp)row.Tag).DefaultValue;
                            columnInfo.ColProp.Identity = ((ColumnProp)row.Tag).Identity;
                            columnInfo.ColProp.IdentityIncrement = ((ColumnProp)row.Tag).IdentityIncrement;
                            columnInfo.ColProp.IdentitySeed = ((ColumnProp)row.Tag).IdentitySeed;
                            columnInfo.ColProp.Precision = ((ColumnProp)row.Tag).Precision;
                            columnInfo.ColProp.Scale = ((ColumnProp)row.Tag).Scale;

                            modifiedTableInfo.Add(columnInfo);
                        }
                    }

                    //Compare the changed set
                    bool isDeletePkScriptReady = false;
                    originalTableInfo.FindAll(o => o.IsDeleted).ForEach(delegate(ColumnInfo colInfo)
                    {
                        if (colInfo.IsPk.HasValue && colInfo.IsPk.Value)
                        {
                            sbTbl.AppendFormat("\nALTER TABLE [{0}] DROP CONSTRAINT {1}", txtTbl.Text.Trim(), pkName);
                            isDeletePkScriptReady = true;
                        }
                        sbTbl.AppendFormat("\nALTER TABLE [{0}] DROP COLUMN [{1}]", txtTbl.Text.Trim(), colInfo.ColumnName);
                    });

                    List<ColumnInfo> existingColumns = originalTableInfo.FindAll(o => !o.IsDeleted);
                    for (int colIndex = existingColumns.Count; colIndex < modifiedTableInfo.Count; colIndex++)
                    {
                        if (modifiedTableInfo[colIndex] != null)
                        {
                            columnProp = modifiedTableInfo[colIndex].ColProp;
                            sbTbl.AppendFormat("\nALTER TABLE [{0}] ADD [{1}] {2}", txtTbl.Text.Trim(), modifiedTableInfo[colIndex].ColumnName, modifiedTableInfo[colIndex].DataType);
                            if (modifiedTableInfo[colIndex].MaxLength.HasValue)
                            {
                                sbTbl.AppendFormat("({0})", modifiedTableInfo[colIndex].MaxLength.Value.ToString());
                            }
                            else
                            {
                                if (modifiedTableInfo[colIndex].DataType == "numeric")
                                {
                                    sbTbl.AppendFormat("({0},{1})", columnProp.Precision > 0 ? columnProp.Precision.ToString() : "18", columnProp.Scale.ToString());
                                }
                            }
                            if ((modifiedTableInfo[colIndex].DataType == "int" || modifiedTableInfo[colIndex].DataType == "bigint") && columnProp.Identity && columnProp.IdentitySeed > 0 && columnProp.IdentityIncrement > 0)
                            {
                                sbTbl.AppendFormat(" IDENTITY({0},{1}) NOT NULL", columnProp.IdentitySeed.ToString(), columnProp.IdentityIncrement.ToString());
                            }
                            else
                            {
                                sbTbl.AppendFormat(" {0}", modifiedTableInfo[colIndex].IsNullable ? "NULL" : " NOT NULL");
                                if (!string.IsNullOrEmpty(columnProp.DefaultValue))
                                {
                                    sbTbl.AppendFormat(" DEFAULT ({0})", columnProp.DefaultValue);
                                }
                            }
                        }
                    }
                    for (int colIndex = 0; colIndex < existingColumns.Count; colIndex++)
                    {
                        if (modifiedTableInfo[colIndex].IsPk != existingColumns[colIndex].IsPk && !isDeletePkScriptReady)
                        {
                            sbTbl.AppendFormat("\nALTER TABLE [{0}] DROP CONSTRAINT {1}", txtTbl.Text.Trim(),pkName);
                            isDeletePkScriptReady = true;
                        }
                    }
                    for (int colIndex = 0; colIndex < existingColumns.Count; colIndex++)
                    {
                        if (modifiedTableInfo[colIndex].DataType != existingColumns[colIndex].DataType
                            || modifiedTableInfo[colIndex].MaxLength != existingColumns[colIndex].MaxLength
                            || modifiedTableInfo[colIndex].IsNullable != existingColumns[colIndex].IsNullable
                            || modifiedTableInfo[colIndex].ColProp.DefaultValue != existingColumns[colIndex].ColProp.DefaultValue
                            || modifiedTableInfo[colIndex].ColProp.Identity != existingColumns[colIndex].ColProp.Identity
                            || modifiedTableInfo[colIndex].ColProp.IdentityIncrement != existingColumns[colIndex].ColProp.IdentityIncrement
                            || modifiedTableInfo[colIndex].ColProp.IdentitySeed != existingColumns[colIndex].ColProp.IdentitySeed
                            || modifiedTableInfo[colIndex].ColProp.Precision != existingColumns[colIndex].ColProp.Precision
                            || modifiedTableInfo[colIndex].ColProp.Scale != existingColumns[colIndex].ColProp.Scale
                            )
                        {
                            columnProp = modifiedTableInfo[colIndex].ColProp;
                            sbTbl.AppendFormat("\nALTER TABLE [{0}] ALTER COLUMN [{1}] {2}",txtTbl.Text.Trim(), modifiedTableInfo[colIndex].ColumnName, modifiedTableInfo[colIndex].DataType);
                            if (modifiedTableInfo[colIndex].MaxLength.HasValue)
                            {
                                sbTbl.AppendFormat("({0})", modifiedTableInfo[colIndex].MaxLength.Value.ToString());
                            }
                            else
                            {
                                if (modifiedTableInfo[colIndex].DataType == "numeric")
                                {
                                    sbTbl.AppendFormat("({0},{1})", columnProp.Precision > 0 ? columnProp.Precision.ToString() : "18", columnProp.Scale.ToString());
                                }
                            }
                            if ((modifiedTableInfo[colIndex].DataType == "int" || modifiedTableInfo[colIndex].DataType == "bigint") && columnProp.Identity && columnProp.IdentitySeed > 0 && columnProp.IdentityIncrement > 0)
                            {
                                sbTbl.AppendFormat(" IDENTITY({0},{1}) NOT NULL", columnProp.IdentitySeed.ToString(), columnProp.IdentityIncrement.ToString());
                            }
                            else
                            {
                                sbTbl.AppendFormat(" {0}", modifiedTableInfo[colIndex].IsNullable ? "NULL" : " NOT NULL");
                                if (!string.IsNullOrEmpty(columnProp.DefaultValue))
                                {
                                    sbTbl.AppendFormat(" DEFAULT ({0})", columnProp.DefaultValue);
                                }
                            }
                        }
                    }
                    if (isDeletePkScriptReady && modifiedTableInfo.FindAll(m => m.IsPk.HasValue && m.IsPk.Value).Count > 0)
                    {
                        StringBuilder sbPk = new StringBuilder();
                        sbPk.AppendFormat("\nALTER TABLE [{0}] ADD PRIMARY KEY (", txtTbl.Text.Trim());
                        for (int colIndex = 0; colIndex < modifiedTableInfo.Count; colIndex++)
                        {
                            if (modifiedTableInfo[colIndex].IsPk.HasValue && modifiedTableInfo[colIndex].IsPk.Value)
                            {
                                sbPk.AppendFormat("[{0}],", modifiedTableInfo[colIndex].ColumnName);
                            }
                        }
                        sbTbl.Append(sbPk.ToString().Substring(0, sbPk.ToString().Length - 1) + ")");
                    }
                    TableScript = sbTbl.ToString();
                }
                btnHdnTbl.PerformClick();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dgTbl_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            try
            {
                if (isEditMode)
                {
                    originalTableInfo.FindAll(o => !o.IsDeleted)[e.RowIndex].IsDeleted = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }        
    }
    public class ColumnProp
    {
        [CategoryAttribute("Column Properties"),
        DescriptionAttribute("Default Value")]
        public string DefaultValue { get; set; }

        [CategoryAttribute("Column Properties"),
        DescriptionAttribute("Specify if the column is IDENTITY Column")]
        public bool Identity { get; set; }

        [CategoryAttribute("Column Properties"),
        DescriptionAttribute("Specify IDENTITY Seed")]
        public int IdentityIncrement { get; set; }

        [CategoryAttribute("Column Properties"),
        DescriptionAttribute("Specify IDENTITY Increment")]
        public int IdentitySeed { get; set; }

        //[CategoryAttribute("Column Properties"),
        //DescriptionAttribute("Specify if the Column contain GUID")]
        //public bool IsRowGuid { get; set; }

        [CategoryAttribute("Column Properties"),
        DescriptionAttribute("Specify Precision if the column is Numeric Column")]
        public int Precision { get; set; }

        [CategoryAttribute("Column Properties"),
        DescriptionAttribute("Specify Scale if the column is Numeric Column")]
        public int Scale { get; set; }        
    }

    public class ColumnInfo
    {
        public int ColIndex { get; set; }
        public string ColumnName { get; set; }
        public string DataType { get; set; }
        public int? MaxLength { get; set; }
        public bool IsNullable { get; set; }
        public bool? IsPk { get; set; }
        public ColumnProp ColProp { get; set; }
        public bool IsDeleted { get; set; }
        public bool IsExisting { get; set; }
        public bool IsAdded { get; set; }
    }
}
